import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, Typography, message, Tabs, QRCode, Spin, Alert } from 'antd';
import { UserOutlined, LockOutlined, QrcodeOutlined, ReloadOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import { API_CONFIG, APP_CONFIG } from '../../config';
import './index.css';

const { Title, Text } = Typography;
const { TabPane } = Tabs;

interface LoginForm {
  username: string;
  password: string;
}

const Login: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();

  // 扫码登录相关状态
  const [qrContent, setQrContent] = useState<string>('');
  const [qrStatus, setQrStatus] = useState<'waiting' | 'scanning' | 'confirmed' | 'expired'>('waiting');
  const [qrLoading, setQrLoading] = useState<boolean>(false);
  const [activeTab, setActiveTab] = useState<string>('password');
  const [pollingInterval, setPollingInterval] = useState<NodeJS.Timeout | null>(null);

  // 生成二维码
  const generateQrCode = async () => {
    try {
      setQrLoading(true);
      setQrStatus('waiting');
      
      const response = await axios.post(`${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.AUTH.QR_GENERATE}`);

      if (response.data.code === 200) {
        const { sessionId, qrContent } = response.data.data;
        setQrContent(qrContent);
        setQrStatus('waiting');

        // 开始轮询登录状态
        startPolling(sessionId);
      } else {
        message.error(response.data.message || '生成二维码失败');
      }
    } catch (error) {
      console.error('生成二维码失败:', error);
      message.error('生成二维码失败，请重试');
    } finally {
      setQrLoading(false);
    }
  };

  // 轮询登录状态
  const startPolling = (sessionId: string) => {
    // 清除之前的轮询
    if (pollingInterval) {
      clearInterval(pollingInterval);
    }

    const interval = setInterval(async () => {
      try {
        const response = await axios.get(`${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.AUTH.QR_STATUS}?sessionId=${sessionId}`);

        if (response.data.code === 200) {
          const { status, accessToken, userInfo } = response.data.data;

          if (status === 'confirmed') {
            clearInterval(interval);
            setQrStatus('confirmed');

            // 保存登录状态
            localStorage.setItem(APP_CONFIG.LOGIN.TOKEN_KEY, accessToken);
            localStorage.setItem(APP_CONFIG.LOGIN.USER_INFO_KEY, JSON.stringify({
              id: userInfo.openId,
              username: userInfo.nickname,
              name: userInfo.nickname,
              role: 'admin',
              avatar: userInfo.avatarUrl
            }));

            message.success('扫码登录成功！');
            navigate(APP_CONFIG.ROUTES.DASHBOARD);
          } else if (status === 'expired') {
            clearInterval(interval);
            setQrStatus('expired');
            message.error('二维码已过期，请重新生成');
          }
        }
      } catch (error) {
        console.error('轮询登录状态失败:', error);
      }
    }, API_CONFIG.POLLING.INTERVAL);

    setPollingInterval(interval);

    // 设置超时停止轮询
    setTimeout(() => {
      clearInterval(interval);
      if (qrStatus === 'waiting') {
        setQrStatus('expired');
      }
    }, API_CONFIG.POLLING.TIMEOUT);
  };

  // 切换到扫码登录时自动生成二维码
  useEffect(() => {
    if (activeTab === 'qrcode') {
      generateQrCode();
    } else {
      // 切换到其他tab时清除轮询
      if (pollingInterval) {
        clearInterval(pollingInterval);
        setPollingInterval(null);
      }
    }
  }, [activeTab]);

  // 组件卸载时清除轮询
  useEffect(() => {
    return () => {
      if (pollingInterval) {
        clearInterval(pollingInterval);
      }
    };
  }, [pollingInterval]);

  const onFinish = async (values: LoginForm) => {
    try {
      // 模拟登录API调用
      console.log('登录信息:', values);

      // 这里应该调用实际的登录API
      // const response = await loginAPI(values);

      // 模拟登录成功
      if (values.username === APP_CONFIG.LOGIN.DEFAULT_USERNAME && 
          values.password === APP_CONFIG.LOGIN.DEFAULT_PASSWORD) {
        // 保存登录状态
        localStorage.setItem(APP_CONFIG.LOGIN.TOKEN_KEY, 'mock-jwt-token');
        localStorage.setItem(APP_CONFIG.LOGIN.USER_INFO_KEY, JSON.stringify({
          id: 1,
          username: 'admin',
          name: '系统管理员',
          role: 'admin'
        }));

        message.success('登录成功！');
        navigate(APP_CONFIG.ROUTES.DASHBOARD);
      } else {
        message.error('用户名或密码错误！');
      }
    } catch {
      message.error('登录失败，请重试！');
    }
  };

  // 获取二维码状态提示
  const getQrStatusMessage = () => {
    switch (qrStatus) {
      case 'waiting':
        return '请使用微信扫描二维码登录';
      case 'scanning':
        return '正在扫描，请稍候...';
      case 'confirmed':
        return '登录成功，正在跳转...';
      case 'expired':
        return '二维码已过期，请重新生成';
      default:
        return '请使用微信扫描二维码登录';
    }
  };

  // 获取二维码状态类型
  const getQrStatusType = () => {
    switch (qrStatus) {
      case 'waiting':
        return 'info';
      case 'scanning':
        return 'warning';
      case 'confirmed':
        return 'success';
      case 'expired':
        return 'error';
      default:
        return 'info';
    }
  };

  return (
    <div className="login-container">
      <div className="login-content">
        <Card className="login-card">

          <div className="login-header">
            <Title level={2}>{APP_CONFIG.NAME}</Title>
            <Text type="secondary">{APP_CONFIG.DESCRIPTION}</Text>
          </div>

          <div className='content-row'>
            <div className='login-image'></div>
            <Tabs 
              activeKey={activeTab} 
              onChange={setActiveTab}
              centered
              size="large"
              className="login-tabs"
            >
              
              <TabPane 
                tab={
                  <span>
                    <UserOutlined />
                    账号密码登录
                  </span>
                } 
                key="password"
              >
                
                <Form
                  form={form}
                  name="login"
                  onFinish={onFinish}
                  autoComplete="off"
                  size="large"
                >
                  <Form.Item
                    name="username"
                    rules={[
                      { required: true, message: '请输入用户名!' },
                      { min: 3, message: '用户名至少3个字符!' }
                    ]}
                  >
                    <Input
                      prefix={<UserOutlined />}
                      placeholder="用户名"
                    />
                  </Form.Item>

                  <Form.Item
                    name="password"
                    rules={[
                      { required: true, message: '请输入密码!' },
                      { min: 6, message: '密码至少6个字符!' }
                    ]}
                  >
                    <Input.Password
                      prefix={<LockOutlined />}
                      placeholder="密码"
                    />
                  </Form.Item>

                  <Form.Item>
                    <Button type="primary" htmlType="submit" block >
                      登录
                    </Button>
                  </Form.Item>
                </Form>
                
                
                <div className="login-footer">
                  <Text type="secondary">
                    默认账号: {APP_CONFIG.LOGIN.DEFAULT_USERNAME} / {APP_CONFIG.LOGIN.DEFAULT_PASSWORD}
                  </Text>
                </div>
              </TabPane>
                


              <TabPane 
                tab={
                  <span>
                    <QrcodeOutlined />
                    微信扫码登录
                  </span>
                } 
                key="qrcode"
              >
                <div className="qrcode-container">
                  {qrLoading ? (
                    <div className="qrcode-loading">
                      <Spin size="large" />
                      <Text>正在生成二维码...</Text>
                    </div>
                  ) : (
                    <>
                      <div className="qrcode-wrapper">
                        {qrStatus === 'expired' ? (
                          <div className="qrcode-expired">
                            <QrcodeOutlined style={{ fontSize: '64px', color: '#ccc' }} />
                            <Text type="secondary">二维码已过期</Text>
                            <Button 
                              type="primary" 
                              icon={<ReloadOutlined />}
                              onClick={generateQrCode}
                              style={{ marginTop: '16px' }}
                            >
                              重新生成
                            </Button>
                          </div>
                        ) : (
                          <QRCode 
                            value={qrContent || 'https://example.com'} 
                            size={200}
                            status={qrStatus === 'confirmed' ? 'expired' : 'active'}
                          />
                        )}
                      </div>
                      
                      <Alert
                        message={getQrStatusMessage()}
                        type={getQrStatusType()}
                        showIcon
                        style={{ marginTop: '16px' }}
                      />
                      
                      <div className="qrcode-tips">
                        <Text type="secondary">
                          <ul style={{ margin: '8px 0', paddingLeft: '20px' }}>
                            {/* <li>请使用微信扫描上方二维码</li>
                            <li>扫码后在小程序中确认登录</li> */}
                            <li>二维码有效期为5分钟</li>
                          </ul>
                        </Text>
                      </div>
                    </>
                  )}
                </div>
              </TabPane>
            </Tabs>
          </div>
          </Card>
       </div>
    </div>
  );
};

export default Login;
